package com.chinasoft.mall.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chinasoft.mall.R;

public class LoadListView extends ListView implements OnScrollListener{
	


	private final static int RELEASE_To_REFRESH = 0;
	private final static int PULL_To_REFRESH = 1;
	private final static int REFRESHING = 2;
	private final static int DONE = 3;
	private final static int LOADING = 4;

	// 实际的padding的距离与界面上偏移距离的比例
	private final static int RATIO = 3;

	private LinearLayout footView;


	// 用于保证startY的值在一个完整的touch事件中只被记录一次
	private boolean isRecored;

	private int headContentWidth;
	private int headContentHeight;

	private int startY;
	private int firstVisibleItem;
	private int visibleItemCount;
	private int totalItemCount;

	private int state;

	private OnRefreshListener refreshListener;

	private boolean isRefreshable;

	View.OnTouchListener mGestureListener;

	public LoadListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
		setFadingEdgeLength(0);
	}

	private void init(Context context) {
		BuildProgressBar();
		measureView(footView);
		headContentHeight = getMeasuredHeight()-footView.getMeasuredHeight();
		headContentWidth = footView.getMeasuredWidth();

		footView.setPadding(0, headContentHeight, 0, 0);
		footView.invalidate();

		Log.v("size", "width:" + headContentWidth + " height:"
				+ headContentHeight);

		addFooterView(footView, null, false);
		setOnScrollListener(this);


		state = DONE;
		isRefreshable = false;
	}

	public void addRefreshHead() {

	}

	public void onScroll(AbsListView view, int firstVisiableItem, int visibleItemCount,
			int totalItemCount) {
		this.firstVisibleItem = firstVisiableItem;
		this.visibleItemCount = visibleItemCount;
		this.totalItemCount = totalItemCount;
	}

	public void onScrollStateChanged(AbsListView arg0, int arg1) {
	}

	public boolean onTouchEvent(MotionEvent event) {
		if (isRefreshable) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if ((firstVisibleItem+visibleItemCount>=totalItemCount-1) && !isRecored) {
					isRecored = true;
					startY = (int) event.getY();
				}
				break;
			case MotionEvent.ACTION_UP:
				if (state != REFRESHING && state != LOADING) {
					if (state == DONE) {
						// 什么都不做
					}
					if (state == PULL_To_REFRESH) {
						state = DONE;
						changeFooterViewByState();
					}
					if (state == RELEASE_To_REFRESH) {
						state = REFRESHING;
						changeFooterViewByState();
						onRefresh();
					}
				}
				isRecored = false;
				break;

			case MotionEvent.ACTION_MOVE:
				int tempY = (int) event.getY();

				if (!isRecored && (firstVisibleItem+visibleItemCount)>=totalItemCount-1) {
					isRecored = true;
					startY = tempY;
				}

				if (state != REFRESHING && isRecored && state != LOADING) {
					// 保证在设置padding的过程中，当前的位置一直是在head，否则如果当列表超出屏幕的话，当在上推的时候，列表会同时进行滚动
					// 可以松手去刷新了
					if (state == RELEASE_To_REFRESH) {
						setSelection(getLastVisiblePosition());
						// 往上推了，推到了屏幕足够掩盖head的程度，但是还没有推到全部掩盖的地步
						if (((startY - tempY) / RATIO < headContentHeight)
								&& (startY - tempY) > 0) {
							state = PULL_To_REFRESH;
							changeFooterViewByState();
						}
						// 一下子推到顶了
						else if (startY - tempY <= 0) {
							state = DONE;
							changeFooterViewByState();
						}
						// 往下拉了，或者还没有上推到屏幕顶部掩盖head的地步
						else {
							// 不用进行特别的操作，只用更新paddingTop的值就行了
						}
					}
					// 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
					if (state == PULL_To_REFRESH) {
						setSelection(getLastVisiblePosition());
						// 下拉到可以进入RELEASE_TO_REFRESH的状态
						if ((startY - tempY) / RATIO >= headContentHeight) {
							state = RELEASE_To_REFRESH;
							changeFooterViewByState();
						}
						// 上推到顶了
						else if (startY - tempY <= 0) {
							state = DONE;
							changeFooterViewByState();
						}
					}

					// done状态下
					if (state == DONE) {
						if (startY - tempY > 0) {
							state = PULL_To_REFRESH;
							changeFooterViewByState();
						}
					}

					// 更新headView的size
					if (state == PULL_To_REFRESH) {
						footView.setPadding(0, headContentHeight
								+ (startY - tempY) / RATIO, 0, 0);

					}

					// 更新headView的paddingTop
					if (state == RELEASE_To_REFRESH) {
						footView.setPadding(0, headContentHeight
								+ (startY - tempY) / RATIO, 0, 0);
					}
				}
				break;
			}
		}

		return super.onTouchEvent(event);
	}

	// 当状态改变时候，调用该方法，以更新界面
	private void changeFooterViewByState() {
		switch (state) {
		case RELEASE_To_REFRESH:
			break;
		case PULL_To_REFRESH:
			break;
		case REFRESHING:
			footView.setPadding(0, 0, 0, 0);
			break;
		case DONE:
			setSelection(getLastVisiblePosition());
			footView.setPadding(0, headContentHeight, 0, 0);
			break;
		}
	}

	public void setonRefreshListener(OnRefreshListener refreshListener) {
		this.refreshListener = refreshListener;
		isRefreshable = true;
	}

	public interface OnRefreshListener {
		public void onRefresh();
	}

	public void onRefreshComplete() {
		state = DONE;
		changeFooterViewByState();
	}

	private void onRefresh() {
		if (refreshListener != null) {
			refreshListener.onRefresh();
		}
	}

	// 此方法直接照搬自网络上的一个下拉刷新的demo，此处是“估计”headView的width以及height
	private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	public void setAdapter(BaseAdapter adapter) {
		super.setAdapter(adapter);
	}

	
	
	
//	private boolean isRepeat=false;
//	private boolean isBottom=false;
//    private LinearLayout headView;//页脚
//	private LvCallback lcb;
//	
//	public LoadListView(Context context) {
//		super(context);
//		init(context);
//	}	
//	
//	public void setLcb(LvCallback lcb) {
//		this.lcb = lcb;
//	}
//
//	private void init(Context context){
//		setOnScrollListener(this);
//		BuildProgressBar();
//		headView.setVisibility(View.GONE);
//	}
//	
//    public LoadListView(Context context, AttributeSet attrs) {
//        super(context, attrs);
//        init(context);
//    }
//    
//    /**
//     * 取消加载图片
//     */
//    public void GoFootLayout(){
//    	headView.setVisibility(View.GONE);
//    	isRepeat=false;
//    }
//    
//
//	@Override
//	public void onScrollStateChanged(AbsListView view, int scrollState) {
//		Log.i("listview", scrollState==OnScrollListener.SCROLL_STATE_FLING?"SCROLL_STATE_FLING":scrollState==OnScrollListener.SCROLL_STATE_IDLE?"SCROLL_STATE_IDLE":scrollState==OnScrollListener.SCROLL_STATE_TOUCH_SCROLL?"SCROLL_STATE_TOUCH_SCROLL":"未知");
//		if(scrollState==OnScrollListener.SCROLL_STATE_TOUCH_SCROLL&&isBottom&&lcb!=null&&!isRepeat){
//			if(lcb.nextPageOperate()){
//				headView.setVisibility(View.VISIBLE);
//				isRepeat=true;
//			}
//		}
//	}
//
//	@Override
//	public void onScroll(AbsListView view, int firstVisibleItem,
//			int visibleItemCount, int totalItemCount) {
//		if(firstVisibleItem+visibleItemCount>=totalItemCount-1){
//			isBottom=true;
//		}else{
//			isBottom=false;
//		}
//	}
//	
//	public interface LvCallback{
//		/**
//		 * 执行下一页操作
//		 * @return  true 存在下一页 显示加载图片 false 不存在下一页，不显示
//		 */
//		public boolean nextPageOperate();
//	}
	
    /**
	    * 创建页脚显示进度条,必须在setAdapter()方法之前调用.
	    * @return
	    */
	    private void BuildProgressBar() {
	        if (this.getFooterViewsCount() != 0) {
	            return;
	        }
	        footView = new LinearLayout(this.getContext());
	        footView.setGravity(Gravity.CENTER);
	        footView.setPadding(0, 0, 0, 0);
	        footView.setOrientation(LinearLayout.HORIZONTAL);
	        footView.setBackgroundColor(0x00ffffff);
	        ProgressBar bar = new ProgressBar(this.getContext());
	        footView.addView(bar);

	        TextView txt = new TextView(this.getContext());
	        txt.setText(R.string.loadinglv);
	        txt.setTextColor(0xff000000);
	        footView.addView(txt);

//	        headView.setVisibility(View.GONE);
//	        this.addFooterView(headView);
	    }
}
